<?php
require 'functions.php';

if ($_SERVER['REQUEST_METHOD']!== 'POST') {
  header('HTTP/1.1 405 Method Not Allowed');
  return;
}

$username = input('username');
$password = input('password');
$code =input('code');
$hasError = false;
$errorBag = ['username' => '','password' => '','code'=>''];

//判断用户是否勾选了记住我
$rememberMe = false;
if (isset($_POST['remember-me']) && $_POST['remember-me'] == 1) {
	$rememberMe = true;
}

$sql = 'select id,user_name,password from users where user_name=?';
$data = query($sql,[$username]);

if (trim($username) == '') {
	$hasError = true;
	$errorBag['username'] = '用户名不得为空';
}else if (strlen($password) < 6) {
	$hasError = true;
	$errorBag['password'] = '密码必须大于6位';
}else if (trim($code) == '') {
	$hasError = true;
	$errorBag['code'] = '验证码不得为空';
}else if ($code != $_SESSION['code']) {
	$hasError = true;
	$errorBag['code'] = '验证码错误';
	unset($_SESSION['code']);
}else if (count($data)>0) {
	$user = $data[0];
	if (password_verify($password,$user['password'])) {
		// 密码正确, 做登录正确的处理
		$hasError = false;
		// 修改登录时间和ip
		$ip = $_SERVER['REMOTE_ADDR'];
		// 判断是否勾选了记住我自动登录，若记住我，则生成remember-token
		if ($rememberMe === true) {
		  $tmp = md5($user['id'].time().mt_rand());
		  $rememberToken = md5(substr($tmp,3,16));
		  $_SESSION['remember-token'] = $rememberToken;
		  $sql = 'update users set last_login=now(),last_login_ip=?,remember_token=? where id=?';
		  $args = [$ip,$rememberToken,$user['id']];
		}else{
		  $sql = 'update users set last_login=now(),last_login_ip=? where id=?';
		  $args = [$ip,$user['id']];
		}
		execute($sql,$args);
		$_SESSION['user'] = $user;
		header('Location:'. url('index'));
		return;
	}else $errorBag['password'] = '密码错误';
}else $errorBag['username'] = '用户不存在';


if ($hasError) {
	$inputBag['username'] = $username;
	$_SESSION['input_bag'] = $inputBag;
	$_SESSION['has_error'] = $hasError;
	$_SESSION['error_bag'] = $errorBag;
	header('Location:'. url('signin'));
}